import router from '@/router'
// import store from '@/store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // 页面进度条
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

// eslint-disable-next-line space-before-function-paren
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)

  const hasToken = getToken()
  console.log(hasToken)

  next()
  NProgress.done()
})

// eslint-disable-next-line space-before-function-paren
// router.beforeEach(async (to, from, next) => {
//   // const routeTo404 = JSON.parse(sessionStorage.getItem('routerTo'))
//   // start progress bar
//   NProgress.start()

//   // set page title
//   document.title = getPageTitle(to.meta.title)

//   const hasToken = getToken()

//   // 有token，如果要去login，则重定向到首页
//   if (hasToken) {
//     if (to.path === '/login') {
//       next({ path: '/' })
//       NProgress.done()
//     } else {
//       // determine whether the user has obtained his permission roles through getInfo
//       const hasRoles = store.getters.roles && store.getters.roles.length > 0
//       if (hasRoles) {
//         next()
//       } else {
//         try {
//           const arr = []
//           await store.dispatch('user/getInfo').then(res => {
//             arr.push(res.role.roleName)
//             store.commit('user/SET_ROLES', arr)
//           })

//           // generate accessible routes map based on roles
//           const accessRoutes = await store.dispatch('permission/generateRoutes', arr)
//           accessRoutes.push({
//             path: '*', redirect: '/404', hidden: true
//           })
//           // dynamically add accessible routes
//           router.addRoutes(accessRoutes)

//           // hack method to ensure that addRoutes is complete
//           // set the replace: true, so the navigation will not leave a history record
//           next({ ...to, replace: true })
//         } catch (error) {
//           // remove token and go to login page to re-login
//           await store.dispatch('user/resetToken')
//           Message.error(error || 'Has Error')
//           next(`/login?redirect=${to.path}`)
//           NProgress.done()
//         }
//       }
//     }
//   } else {
//     // 没有token
//     if (whiteList.indexOf(to.path) !== -1) {
//       next()
//     } else {
//       next(`/login?redirect=${to.path}`)
//       NProgress.done()
//     }
//   }
// })

router.afterEach((to) => {
  // finish progress bar
  NProgress.done()
})

export default router
